import { devDebug } from "../../utils/settings";

Page({
  data: {
    submitLock: 0,
    start_time: '00:00',
    end_time: '23:59',
    start_date: '',
    end_date: '',
    min_date: '',
    max_date: '',
    stadium_idx: -1,
    stadium_id: '',
    stadiumList: [],
    // 结果弹出层
    actPopup: 0,
    failList: []
  },
  onLoad(options) {
    const date = new Date();
    const dateStr = date.Format('yyyy-MM-dd')
    this.setData({
      start_date: dateStr,
      end_date: dateStr,
      min_date: dateStr,
      max_date: new Date(date.getTime() + 7 * 86400000).Format('yyyy-MM-dd')
    });
    this.loadStadiumData();
  },
  async loadStadiumData() {
    let resList = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_stadium',
        data: {
          funcName: 'query',
          searchText: '',
          searchData: {}
        },
        success: (r) => resolve(r.result),
      });
    });
    resList = resList.map(o => {
      return {
        _id: o._id,
        label: `${o.stadium_name} [tel:${o.stadium_phone}]`,
        stadium_name: o.stadium_name,
        start_time: o.start_time,
        end_time: o.end_time,
      }
    })
    this.setData({ stadiumList: resList });
    if (resList.length > 0) {
      this.setData({
        stadium_idx: 0, stadium_id: resList[0]._id,
        start_time: resList[0].start_time, end_time: resList[0].end_time
      })
    }
  },
  onChangeStadium(ev) {
    const idx = ev.detail.value;
    const stadium = this.data.stadiumList[idx];
    this.setData({ stadium_idx: idx, stadium_id: stadium._id, start_time: stadium.start_time, end_time: stadium.end_time });
  },
  onChangeDate(ev) {
    const dateStr = ev.detail.value;
    if (ev.currentTarget.dataset.date == 'start_date') {
      this.setData({ start_date: dateStr });
    }
    if (ev.currentTarget.dataset.date == 'end_date' || dateStr > this.data.end_date) {
      this.setData({ end_date: dateStr });
    }
  },
  onChangeTime(ev) {
    const timeStr = ev.detail.value;
    console.log(timeStr);
    if (ev.currentTarget.dataset.time == 'start_time') {
      this.setData({ start_time: timeStr });
    }
    if (ev.currentTarget.dataset.time == 'end_time' || timeStr > this.data.end_time) {
      this.setData({ end_time: timeStr });
    }
  },
  async onSubmit() {
    if (this.data.stadium_idx + 1) {
      this.setData({ submitLock: 1 });
      const res = await new Promise(resolve => {
        wx.cloud.callFunction({
          name: 'db_appointment',
          data: {
            funcName: 'insertMany',
            addData: {
              stadium_id: this.data.stadium_id,
              dateRange: [this.data.start_date, this.data.end_date],
              timeRange: [this.data.start_time, this.data.end_time],
            }
          },
          success: (r) => resolve(r.result),
          fail: () => resolve()
        });
      })
      if (devDebug) console.log('新建预约结果', res);
      if (res.errMsg) {
        wx.showToast({ title: '操作失败，未知错误', icon: 'none' });
      } else {
        if (res.list.length > 0) {
          this.setData({ actPopup: 1, failList: res.list.map(t => new Date(t).Format('yyyy-MM-dd')) });
        } else {
          wx.showToast({ title: '添加成功', icon: 'none' });
        }
      }
    } else {
      wx.showToast({ title: '请选择球馆', icon: 'none' })
    }
    this.setData({ submitLock: 0 });
  },
  onHidePopup() {
    this.setData({ actPopup: 0 })
  }
})